package com.aperos;

import java.util.List;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public class AperosPasChers extends MapActivity implements Runnable {
	public Context context;
	
	public static final String PREFS_NAME = "AperosPasChersPrefsFile";
	public static SharedPreferences settings;
	private float cheapPrice;
	private float expensivePrice;
	final Handler mHandler = new Handler();
	
	public static MyLocationOverlay myLocationOverlay;
	private MapController mapController;
	public static List<Overlay> mapOverlays;
	private MapView mapView;
	private ProgressDialog dialog;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = this;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        settings = getSharedPreferences(PREFS_NAME, 0);
        
        
        cheapPrice = settings.getFloat("cheapPrice", (float) 3.5);
        expensivePrice = settings.getFloat("expensivePrice", (float) 4.6);
        
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapOverlays = mapView.getOverlays();
        mapController = mapView.getController();
        myLocationOverlay = new MyLocationOverlay(this, mapView);
        
        displayOverlays();
        
        LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        Criteria crit = new Criteria();
        crit.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(crit, true);
        if (provider != null) {
	        Location loc = lm.getLastKnownLocation(provider);
	        if (loc != null) {
	        	mapController.animateTo(new GeoPoint((int)(loc.getLatitude() * 1000000), (int)(loc.getLongitude() * 1000000)));
	        	mapController.setZoom(18);
	        }
        }

        mapOverlays.add(myLocationOverlay);
        myLocationOverlay.enableMyLocation();
        myLocationOverlay.runOnFirstFix(new Runnable() {
            public void run() {
            	try {
            		mapController.animateTo(myLocationOverlay.getMyLocation());
            		mapController.setZoom(15);
            	} catch (Exception e) {
            		e.printStackTrace();
            	}
            }
        });
        
    }
    
    private void initOverlays() {
    	try {
    		mapOverlays.removeAll(mapView.getOverlays());
    		dialog = ProgressDialog.show(this, "", getString(R.string.dialog_loading_bar_list), true);
    		new Thread(this).start();

    	} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    
    private void displayOverlays() {
    	if (Service.listBars != null && Service.listBars.size() > 0) {
        	Drawable cheapItem = context.getResources().getDrawable(R.drawable.beer_mug_yellow_overlay);
        	Drawable middleItem = context.getResources().getDrawable(R.drawable.beer_mug_orange_overlay);
        	Drawable expensiveItem = context.getResources().getDrawable(R.drawable.beer_mug_red_overlay);
        	Drawable cheapItemHH = context.getResources().getDrawable(R.drawable.beer_mug_yellow_hh_overlay);
        	Drawable middleItemHH = context.getResources().getDrawable(R.drawable.beer_mug_orange_hh_overlay);
        	Drawable expensiveItemHH = context.getResources().getDrawable(R.drawable.beer_mug_red_hh_overlay);
        	
        	BarItems cheapBarItems = new BarItems(cheapItem, context);
        	BarItems middleBarItems = new BarItems(middleItem, context);
        	BarItems expensiveBarItems = new BarItems(expensiveItem, context);
        	BarItems cheapBarItemsHH = new BarItems(cheapItemHH, context);
        	BarItems middleBarItemsHH = new BarItems(middleItemHH, context);
        	BarItems expensiveBarItemsHH = new BarItems(expensiveItemHH, context);
        	
        	
        	for (Bar bar : Service.listBars) {
        		if (bar.isInHappyHour() && bar.getPriceBeerHappyHour() != null) {
        			if (bar.getPriceBeerHappyHour() <= cheapPrice) {
	        			cheapBarItemsHH.addOverlay(bar);
	        		} else if (bar.getPriceBeerHappyHour() >= expensivePrice) {
	        			expensiveBarItemsHH.addOverlay(bar);
	        		} else {
	        			middleBarItemsHH.addOverlay(bar);
	        		}
        		} else {
	        		if (bar.getPriceBeer() <= cheapPrice) {
	        			cheapBarItems.addOverlay(bar);
	        		} else if (bar.getPriceBeer() >= expensivePrice) {
	        			expensiveBarItems.addOverlay(bar);
	        		} else {
	        			middleBarItems.addOverlay(bar);
	        		}
        		}
    		}
    	
        	if (cheapBarItems.size() > 0) {
        		mapOverlays.add(cheapBarItems);
        	}
			if (middleBarItems.size() > 0) {
				mapOverlays.add(middleBarItems);		
			}
			if (expensiveBarItems.size() > 0) {
				mapOverlays.add(expensiveBarItems);
			}
			if (cheapBarItemsHH.size() > 0) {
				mapOverlays.add(cheapBarItemsHH);
			}
			if (middleBarItemsHH.size() > 0) {
				mapOverlays.add(middleBarItemsHH);
			}
			if (expensiveBarItemsHH.size() > 0) {
				mapOverlays.add(expensiveBarItemsHH);
			}
        	
        }
    }

    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case 1:
                return new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
        }
        return null;
    }
   
    public View getInfosView() {
    	return (View) findViewById(R.layout.view_info);
    }
    

	@Override
	protected boolean isRouteDisplayed() {
		 return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	/**
	 * Action des boutons du menu
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.menu_add_bar:  
	        	//if (myLocationOverlay.getMyLocation() != null) { 
	        		Intent intent = new Intent(this, BarEdit.class);
	        		this.startActivity(intent);
	        	//} else {
	        	//	Toast.makeText(this, this.getString(R.string.error_dialog_text), 1000).show();
	        	//}
	        	break;
	        case R.id.menu_my_position: 
	        	myLocationOverlay.runOnFirstFix(new Runnable() {
	                public void run() {
	                	try {
	                		mapController.animateTo(myLocationOverlay.getMyLocation());
	                		mapController.setZoom(18);
	                	} catch (Exception e) {
	                		e.printStackTrace();
	                	}
	                }
	            });
	        	break;
	        case R.id.menu_init_list:
	        	initOverlays();
	        	break;
	        case R.id.menu_prefs:
	        	Intent intent2 = new Intent(this, PrefsEdit.class);
        		this.startActivity(intent2);
	        	break;
	    }
	    return true;
	}

	@Override
	public void run() {
		try {
	        Service.initListBars(context);
			displayOverlays();
			mHandler.post(mUpdateResults);
		 } catch (Exception e) {
		    e.printStackTrace();
		    mHandler.post(mUpdateError);
		 }
	}
	
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
        	try {
        		dialog.dismiss();
        		updateMapView();
        	} catch (Exception e) {
				e.printStackTrace();
			}
        }
    };
    
    final Runnable mUpdateError = new Runnable() {
        public void run() {
        	try {
        		dialog.dismiss();
        		displayError();
        	} catch (Exception e) {
				e.printStackTrace();
			}
        }
    };
    
    public void updateMapView() {
    	try {
    		mapController.zoomOut();
    		mapController.zoomIn();
    	} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
	public void displayError() {
		try {
			Toast.makeText(context, R.string.error_get_bars_list, 2000).show();
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
}

